package com.ctgu.rabbitmq.rabbitmq.queue.queueExpired;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ ClassName QueueExpiredConfig
 * @ Author Alex2
 * @ Date 2025/8/15 11:17
 **/
@Configuration
public class QueueExpiredConfig {

    // 正常交换机
    public static final String NORMAL_EXCHANGE_QUEUE_EXPIRED = "normal_exchange_queue_expired";
    public static final String NORMAL_QUEUE_QUEUE_EXPIRED = "normal_queue_queue_expired";
    public static final String NORMAL_ROUTING_KEY_QUEUE_EXPIRED = "normal_routing_key_queue_expired";

    // 死信交换机
    public static final String DLX_EXCHANGE_QUEUE_EXPIRED = "dlx_exchange_queue_expired";
    public static final String DLX_QUEUE_QUEUE_EXPIRED = "dlx_queue_queue_expired";
    public static final String DLX_ROUTING_KEY_QUEUE_EXPIRED = "dlx_routing_key_queue_expired";

    @Bean
    public DirectExchange normalExchangeQueueExpired() {
        return new DirectExchange(NORMAL_EXCHANGE_QUEUE_EXPIRED);
    }

    @Bean
    public DirectExchange dlxExchangeQueueExpired() {
        return new DirectExchange(DLX_EXCHANGE_QUEUE_EXPIRED);
    }

    // 队列级 TTL + 死信队列绑定
    @Bean
    public Queue normalQueueQueueExpired() {
        return QueueBuilder.nonDurable(NORMAL_QUEUE_QUEUE_EXPIRED)
                .withArgument("x-dead-letter-exchange", DLX_EXCHANGE_QUEUE_EXPIRED)
                .withArgument("x-dead-letter-routing-key", DLX_ROUTING_KEY_QUEUE_EXPIRED)
                .withArgument("x-message-ttl", 5000) // 队列过期时间 5000ms
                .build();
    }

    @Bean
    public Queue dlxQueueQueueExpired() {
        return QueueBuilder.nonDurable(DLX_QUEUE_QUEUE_EXPIRED).build();
    }

    @Bean
    public Binding bindingNormalQueueQUEUEExpired() {
        return BindingBuilder.bind(normalQueueQueueExpired())
                .to(normalExchangeQueueExpired())
                .with(NORMAL_ROUTING_KEY_QUEUE_EXPIRED);
    }

    @Bean
    public Binding bindingDlxQueue() {
        return BindingBuilder.bind(dlxQueueQueueExpired())
                .to(dlxExchangeQueueExpired())
                .with(DLX_ROUTING_KEY_QUEUE_EXPIRED);
    }
}
